 /* Jostick Light
  * ------------
  *
  * Reads two analog pins connected to a 2D jostick made of two potentiometers,
  * varies intensity of RGB LED.
  *
  */

 int joyUD = 0;       // slider variable connecetd to analog pin 0
 int joyLR = 1;       // slider variable connecetd to analog pin 1
 int UD = 0;          // variable to read the value from the analog pin 0 (Up, Down)
 int LR = 0;          // variable to read the value from the analog pin 1 (Left, Right)

 int redVal   = 0;    // Variables to store the values to send to the pins
 int greenVal = 0;  
 int blueVal  = 0;

 int redPin   = 9;    // Red LED,   connected to digital pin 9,  PWM
 int greenPin = 10;   // Green LED, connected to digital pin 10, PWM
 int bluePin  = 11;   // Blue LED,  connected to digital pin 11, PWM

/*
  From joyMonitor
    Center(ave) -> UD = 583, LR = 469
    Up         = 1023
    Down(ave)  = 83
    Left       = 0
    Right(ave) = 968

*/

  int up     = 1023;
  int dwn    = 80;
  int left   = 0;
  int right  = 980;
  int midUD  = 570;
  int midLR  = 470;
  
  int bright = 255;
  int dim    = 0;
  
  int offBox   = 25; // All LED off zone of this square, ideal = 0
  
 void setup() {
  pinMode(redPin,   OUTPUT);   // sets the pins as output
  pinMode(greenPin, OUTPUT);   
  pinMode(bluePin,  OUTPUT); 
  
 }
 
 void loop() {

  UD = analogRead(joyUD);   // reads the value of the variable resistor 
  LR = analogRead(joyLR);   // reads the value of the variable resistor 
  
  // UD & LR are digital representations of voltage across variable resistors in joystick
  // 10 bit digital rep gives a value between 0-1023 
  // digital PWM output is from 0-255 (0 to 5VDC)
  
/*
Joystick:
  Center        = No R,   No G,   No B
  Up            = No R,   No G,   Full B
  Down          = Full R, No G,   No B
  Left          = No R,   Full G, No B
  Right         = Full All (White)
*/

//UP & DOWN
  if (UD < midUD)
  {
    redVal  = map(UD, dwn, midUD, bright, dim); // down->bright, middle U/D->dim
    blueVal = 0;
  }
  else if (UD >= midUD)
  {
    redVal   = 0;
    blueVal  = map(UD, midUD, up, dim, bright);
  }
    
//LEFT & RIGHT
  if (LR < midLR)
  {
    greenVal = map(LR, midLR, left, dim, bright);
  }
  else if (LR >= midLR)
  {
    greenVal = map(LR, midLR, right, dim, bright);
    
    redVal  = max(redVal, greenVal);  // take which ever give higher intensity LR or UD 
    blueVal = max(blueVal, greenVal);
  } 
  
// Adjust for common anode LEDs (Opposite: ON=LOW(0), OFF=HIGH(255))
    redVal = 255 - redVal;
    blueVal = 255 - blueVal;
    greenVal = 255 - greenVal;

// Create OFF area in center of joystick
  if (UD > midUD - offBox && UD < midUD + offBox && LR > midLR - offBox && LR < midLR + offBox) 
  {
    blueVal = 255; 
    redVal = 255; 
    greenVal = 255;
  }
  
// Write current values to LED pins
  analogWrite(redPin,   redVal);
  analogWrite(greenPin, greenVal); 
  analogWrite(bluePin,  blueVal);  
}

